import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  BadRequestException,
} from '@nestjs/common'

@Catch(BadRequestException)
export class ValidationExceptionFilter implements ExceptionFilter {
  catch(exception: BadRequestException, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const response = ctx.getResponse()
    const request = ctx.getRequest()

    const status = exception.getStatus()
    const exceptionResponse = exception.getResponse() as any

    // 处理class-validator验证错误
    let validationErrors: string[] = []
    let message = '请求参数验证失败'

    if (exceptionResponse.message && Array.isArray(exceptionResponse.message)) {
      validationErrors = this.formatValidationErrors(exceptionResponse.message)
      message = validationErrors.join(', ')
    }

    const responseBody = {
      data: null,
      code: status,
      message: message,
      errors: validationErrors,
      path: request.url,
      timestamp: new Date().toISOString(),
    }

    response.status(status).json(responseBody)
  }

  private formatValidationErrors(errors: any[]): string[] {
    return errors
      .map((error) => {
        if (typeof error === 'string') {
          return error
        }
        if (error.constraints) {
          const values: string[] = Object.values(error.constraints)
          return values
        }
        return '参数验证错误'
      })
      .flat()
  }
}
